package by.averianov.discounta.webapp.page.create;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.apache.commons.mail.EmailException;
import org.apache.wicket.Page;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow.PageCreator;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.DropDownChoice;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.string.StringValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import by.averianov.discounta.datamodel.UserAccount;
import by.averianov.discounta.datamodel.UserProfile;
import by.averianov.discounta.datamodel.enums.AccessGroup;
import by.averianov.discounta.services.EmailSender;
import by.averianov.discounta.services.UserService;
import by.averianov.discounta.webapp.page.BaseLayout;
import by.averianov.discounta.webapp.page.homepage.HomePage;

public class CreateUser extends BaseLayout {

	private static final Logger LOGGER = LoggerFactory.getLogger(CreateUser.class);
	
	protected Long id;
	protected String userEmail;
	protected String userPassword;
	protected AccessGroup accessGroup;
	protected String userFirstName;
	protected String userLastName;
	protected Long phoneNumber;
	protected Boolean userStatus;
	protected String activateCode;
	
	public IModel<String> changeCreate;
	private PageCreator pageCreator;

	public CreateUser(UserAccount userAccount, UserProfile userProfile, PageCreator pageCreator) {
		super(null);
		
		this.pageCreator = pageCreator;
		try {
			this.id = userProfile.getId();
			this.userEmail = userAccount.getUserEmail();
			this.userPassword = userAccount.getUserPassword();
			this.userStatus = userAccount.getUserStatus();
			this.accessGroup = userProfile.getAccessGroup();
			this.userFirstName = userProfile.getUserFirstName();
			this.userLastName = userProfile.getUserLastName();
			this.phoneNumber = userProfile.getPhoneNumber();
			this.activateCode = userAccount.getActivateCode();
			LOGGER.debug("Changing a card");
		} catch (Exception e) {
			LOGGER.debug("Creating a card, card is " + e.getMessage());
			this.id = null;
			this.accessGroup = AccessGroup.user;
			this.activateCode = userService.randomString(8);
			this.userStatus = false;
		}		
	}
	
	@Inject
	private UserService userService;
	
	@Inject
	private EmailSender emailSender;

	@Override
	protected void onInitialize() {
		super.onInitialize();
		
		if(userService.getAllUserProfile().size() == 0) {
			this.accessGroup = AccessGroup.administrator;
			this.userStatus = true;
		}
		String currentPassword = userPassword;
		
		/*if (AuthenticatedWebSession.get().isSignedIn()) {
			HomePage page = new HomePage();
			page.info(new ResourceModel("p.login.youhavealogin").getObject());
			setResponsePage(page);
		}*/
		
		ArrayList<AccessGroup> AccessGroupList = new ArrayList<AccessGroup>();
		AccessGroup[] accessGroups = AccessGroup.values(); 
        for (AccessGroup ag : accessGroups) { 
        	AccessGroupList.add(ag); 
        } 

		final Label labelUserId = new SecuredLabelForAdmin("labelUserId",  Model.of(id)) {};
		final TextField<String> userEmailText = new TextField<String>("userEmail", Model.of(userEmail));
		final PasswordTextField userPasswordText = new PasswordTextField("userPassword", Model.of(currentPassword));
		userPasswordText.setResetPassword(false);		
		final DropDownChoice<AccessGroup> accessGroupDropDown = new SecuredDropDownChoiceForAdmin<AccessGroup>("accessGroup", new PropertyModel<AccessGroup>(this, "accessGroup"), AccessGroupList) {};
		final Label labelAccessGroup = new SecuredLabelForAdmin("labelAccessGroup", getLabelAccessGroup()) {};
		final Label labelUserStatus = new SecuredLabelForAdmin("labelUserStatus", getLabelUserStatus()) {};
		final Label labelActivateCode = new SecuredLabelForAdmin("labelActivateCode", getLabelActivateCode()) {};
		final TextField<String> userFirstNameText = new TextField<String>("userFirstName", Model.of(userFirstName));
		final TextField<String> userLastNameText = new TextField<String>("userLastName", Model.of(userLastName));
		final TextField<Long> phoneNumberLong = new TextField<Long>("phoneNumber", Model.of(phoneNumber));
		final CheckBox userStatusCheckbox = new SecuredAdminCheckBoxAdmin("userStatus", Model.of(userStatus)) {};
		final TextField<String> userActivateCodeText = new SecuredAdminTextFieldAdmin<String>("activateCode", Model.of(activateCode)) {};
		
		Form<?> form = new Form<Void>("userCreateForm") {
			@Override
			protected void onSubmit() {

				Page page = pageCreator.createPage();
				
				PageParameters pageParameters = new PageParameters();
				
				pageParameters.add("userEmailText", userEmailText.getModelObject());
				pageParameters.add("userPasswordText", userPasswordText.getModelObject());
				//pageParameters.add("accessGroupDropDown", accessGroupDropDown.getModelObject());
				pageParameters.add("userFirstNameText", userFirstNameText.getModelObject());
				pageParameters.add("userLastNameText", userLastNameText.getModelObject());
				pageParameters.add("phoneNumberLong", phoneNumberLong.getModelObject());
				//pageParameters.add("userStatusCheckbox", userStatusCheckbox.getModelObject());
				pageParameters.add("userActivateCodeText", userActivateCodeText.getModelObject());
				StringValue userEmailValue = pageParameters.get("userEmailText");
				StringValue userPasswordValue = pageParameters.get("userPasswordText");
				//StringValue accessGroupDropDownValue = pageParameters.get("accessGroupDropDown");
				StringValue userFirstNameValue = pageParameters.get("userFirstNameText");
				StringValue userLastNameValue = pageParameters.get("userLastNameText");
				StringValue phoneNumberValue = pageParameters.get("phoneNumberLong");
				//StringValue serStatusCheckbox = pageParameters.get("userStatusCheckbox");
				StringValue userActivateCodeValue = pageParameters.get("userActivateCodeText");
				
				userEmail = userEmailValue.toString();
				userPassword = userPasswordValue.toString();
				accessGroup = accessGroupDropDown.getModelObject();
				userFirstName = userFirstNameValue.toString();
				userLastName = userLastNameValue.toString();
				activateCode = userActivateCodeValue.toString();
				userStatus = userStatusCheckbox.getModelObject().booleanValue();
				
				if(userEmail == null & userPassword == null) {
					error(new ResourceModel("p.error.logpassnotnull").getObject());
				} else {		
		        
					UserAccount account = userService.createUserAccount(userEmail, userPassword, userStatus, activateCode);
					UserProfile profile = userService.createUserProfile(id, userFirstName, userLastName, userService.getCurrentDate(), Long.parseLong(phoneNumberValue.toString()), accessGroup);
					userService.saveOrUpdateUser(profile, account);
					
					
					if (!userStatus) {
						try {
							List<String> emailParameters = new ArrayList<String>();
							emailParameters.add(getDNS().getObject());
							emailParameters.add(getPort().getObject());
							emailParameters.add(getLabelAbout().getObject());
							emailParameters.add(getEmailTemplate1().getObject());
							emailParameters.add(getEmailTemplate2().getObject());
							emailParameters.add(getEmailTemplate3().getObject());
							emailParameters.add(getEmailTemplate4().getObject());					
							
							emailSender.sendEmailConfirm(profile, emailParameters);
							page.info(new ResourceModel("p.info.activationemailsending").getObject());
						} catch (EmailException e) {
							page = new HomePage();
							page.error(new ResourceModel("p.error.crashsendemail").getObject() + " " + e.toString());
							setResponsePage(page);
							
						}
					}
				}
				setResponsePage(page);
				
			}
		};		 
		add(form);
				
		Label labelCreateUser = new Label("labelCreateUser", getLabelCreateUser(id));
		form.add(labelCreateUser);
		
		Label labelUserIdText = new SecuredLabelForAdmin("labelUserIdText", getLabelUserIdText()) {};
		if(id == null){
			labelUserIdText = new Label("labelUserIdText", "");
		}
		form.add(labelUserIdText);						
		
		form.add(labelUserId);		
		form.add(userEmailText);
		form.add(userPasswordText);
		form.add(accessGroupDropDown);
		form.add(labelAccessGroup);
		form.add(userFirstNameText);
		form.add(userLastNameText);
		form.add(phoneNumberLong);		
		form.add(userStatusCheckbox);
		form.add(userActivateCodeText);
		form.add(labelUserStatus);
		form.add(labelActivateCode);
		
		form.add(new Label("labelSave", getButtonSave()));
		
		Link linkCancel = new Link("linkCancel"){
			@Override
			public void onClick() {
				setResponsePage(pageCreator.createPage());
				
			}
		};
		linkCancel.add(new Label("labelCancel", getButtonCancel()));
		form.add(linkCancel);
	}
}
